package com.cskaoyan.service.impl;

import com.cskaoyan.bean.PageParameter;
import com.cskaoyan.mapper.MarketTopicMapper;
import com.cskaoyan.model.MarketTopic;
import com.cskaoyan.model.MarketTopicExample;
import com.cskaoyan.service.TopicService;
import com.cskaoyan.utils.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class TopicServiceImpl implements TopicService {

    @Override
    public void create(MarketTopic marketTopic) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketTopicMapper mapper = sqlSession.getMapper(MarketTopicMapper.class);
        marketTopic.setAddTime(new Date());
        marketTopic.setUpdateTime(new Date());
        marketTopic.setDeleted(false);

        mapper.insertSelective(marketTopic);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void update(MarketTopic marketTopic) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        marketTopic.setUpdateTime(new Date());

        MarketTopicMapper mapper = sqlSession.getMapper(MarketTopicMapper.class);
        mapper.updateByPrimaryKeySelective(marketTopic);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void delete(MarketTopic marketTopic) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        marketTopic.setDeleted(true);

        MarketTopicMapper mapper = sqlSession.getMapper(MarketTopicMapper.class);
        mapper.updateByPrimaryKeySelective(marketTopic);

        sqlSession.commit();
        sqlSession.close();

    }


    @Override
    public List<MarketTopic> getTopicListPaged(PageParameter pageParameter, Map<String, String[]> map) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketTopicMapper mapper = sqlSession.getMapper(MarketTopicMapper.class);
        MarketTopicExample example = new MarketTopicExample();
        example.setOrderByClause(pageParameter.getSort() + " " + pageParameter.getOrder());
        MarketTopicExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        // title: 111
        //subtitle: 222
        String[] titles = map.get("title");
        if (titles != null && titles[0] != null && !titles[0].isEmpty()) {
            criteria.andTitleLike("%" + titles[0] + "%");
        }
        String[] subtitles = map.get("subtitle");
        if (subtitles != null && subtitles[0] != null && !subtitles[0].isEmpty()) {
            criteria.andSubtitleLike("%" + subtitles[0] + "%");
        }
        PageHelper.startPage(pageParameter.getPage(), pageParameter.getLimit());
        List<MarketTopic> marketTopics = mapper.selectByExample(example);
        sqlSession.commit();
        sqlSession.close();
        return marketTopics;
    }
}
